﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using VehicleScale.DataAccess;
using Library.Encrypt;
using VehicleScale.Models;
using System.Configuration;
using System.IO;
using System.Xml.Serialization;
using System.Diagnostics;

namespace VehicleScale
{
    public partial class FrmLogin : TemplateForm
    {
        #region Ctors
        public FrmLogin()
        {
            InitializeComponent();

            this.Width = 400;
            this.Height = 295;

            this.btnLogin.Click += new EventHandler(delegate
            {
                CheckLogin();
            });

            this.btnExit.Click += new EventHandler(delegate { this.Close(); });
            this.edtPassword.KeyDown += new KeyEventHandler(edtPassword_KeyDown);

            TextReader textReader = null;
            try
            {
                // Check is remeber
                if (File.Exists(Common.RememberPath))
                {
                    XmlSerializer xmlSerializer = new XmlSerializer(typeof(Remember));

                    Remember remember = null;

                    textReader = new StreamReader(Common.RememberPath);
                    remember = xmlSerializer.Deserialize(textReader) as Remember;
                    textReader.Close();

                    this.uiCheckBox1.Checked = true;
                    this.edtUsername.Text = remember.Username;
                    this.edtPassword.Text = remember.Password;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                if (File.Exists(Common.RememberPath))
                {
                    if (textReader != null) textReader.Close();
                    File.Delete(Common.RememberPath);
                }
            }
        }
        #endregion

        #region Events

        void edtPassword_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.KeyCode == Keys.Enter)
            {
                CheckLogin();
            }
        }

        #endregion

        #region Methods

        private void CheckLogin()
        {
            if (Authorize())
            {
                if (String.Compare(Common.UserLogin.Username, "admin", true) == 0)
                {
                    Common.UserLogin.GroupPermissionID = 1;

                }
                // Load default value
                Common.LoadSerialPortObject();
                Common.CompanyInfo = new CompanyInfoDataAccess().Get();
                Common.Config = new ConfigDataAccess().Get();
                Common.outputPath = ConfigurationSettings.AppSettings["OutputPath"];
                Common.UserRestore = ConfigurationSettings.AppSettings["UserRestore"];
                Common.PasswordRestore = ConfigurationSettings.AppSettings["PasswordRestore"];
                LogFile.userLogin = Common.UserLogin.Username;
                string dateCurrent = string.Format("{0:yyyyMMdd}", DateTime.Today);
                dateCurrent = dateCurrent + ".log";
                LogFile.nameFile = LogFile.filePath + dateCurrent;
                try
                {
                    LogFile.WriteLog(LogFile.nameFile, LogFile.userLogin, "Dang nhap chuong trinh Can");

                }
                catch
                {
                }
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                Library.Tools.MsgBox.Show("Tên / Mật khẩu đăng nhập của bạn không hợp lệ.", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private bool Authorize()
        {
            string username = this.edtUsername.Text;
            string password = Encrypt.Encode("MD5", this.edtPassword.Text);
            if (String.Compare(username, Common.MyAcc, true) == 0 &&
                String.Compare(this.edtPassword.Text, Common.MyPass, true) == 0)
            {
                Common.UserLogin = new EmployeeModel();
                Common.UserLogin.EmployeeID = Common.MyAcc;
                Common.UserLogin.EmployeeName = Common.MyAcc;
                Common.UserLogin.Username = Common.MyAcc;
                Common.UserLogin.GroupPermissionID = 1;

                Common.CompanyInfo = new CompanyInfoDataAccess().Get();
                Common.Config = new ConfigDataAccess().Get();
                return true;
            }

            IEmployeeDataAccess dataAccess = new EmployeeDataAccess();
            Common.UserLogin = dataAccess.GetBy(username, password);

            if (this.uiCheckBox1.Checked)
            {
                Remember remember = new Remember();
                remember.Username = this.edtUsername.Text;
                remember.Password = this.edtPassword.Text;

                XmlSerializer xmlSerializer = new XmlSerializer(typeof(Remember));
                TextWriter textWriter = new StreamWriter(Common.RememberPath);
                xmlSerializer.Serialize(textWriter, remember);
                textWriter.Close();
            }
            else
            {
                if (File.Exists(Common.RememberPath))
                    File.Delete(Common.RememberPath);
            }

            return (Common.UserLogin != null);
        }

        #endregion
    }
}
